import re
import threading

import PySimpleGUI as sg
import ping3


def ping(ip):
    """
    Ping an IP address and return True if successful, False otherwise.
    """
    r = ping3.ping(ip, timeout=1)
    if r is not None:
        return ip, True
    else:
        return ip, False


def ping_range(ip_base, ip_range):
    """Ping a range of IP addresses and return the results."""
    results = []
    start = int(ip_base.split('.')[-1])
    end = int(ip_range)
    prefix_ip = '.'.join(ip_base.split('.')[0:-1])
    global starting
    for i in range(start, end):
        if not starting:
            break
        ip = f"{prefix_ip}.{i}"
        ip, is_reachable = ping(ip)
        if is_reachable:
            results.append(f"网络通: {ip}")
        else:
            results.append(f"网络不通: {ip}")
        # Update the GUI window with the new result
        window['-TEXTAREA-'].update('\n'.join(results))
        window.refresh()  # Refresh the window to show the updated text
    results.append("停止...")
    window['-TEXTAREA-'].update('\n'.join(results))
    window.refresh()
    starting = False
    return results


# Define the layout of the GUI
layout = [
    [sg.Text('IP 地址'), sg.InputText(key='-IP-', size=15), sg.Text('范围'), sg.InputText(key='-RANGE-', size=5)],
    [sg.Button('开始'), sg.Button('停止'), sg.Button('退出')],
    [sg.Text('Results')],
    [sg.Multiline(size=(50, 10), key='-TEXTAREA-', autoscroll=True)]
]

# Create the window
window = sg.Window('IP Range Pinger', layout)

# 正则表达式用于验证 IP 地址
ip_pattern = re.compile(r'^\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}$')


def is_valid_ip(ip):
    """验证 IP 地址是否有效"""
    return bool(ip_pattern.match(ip))


# 数字范围1-255之间
num_pattern = re.compile(r'^(?:1\d\d|2[0-4]\d|25[0-5]|\d{1,2})$')


def is_valid_num(num):
    """验证数字是否有效"""
    return bool(num_pattern.match(num))


starting = False
# Event loop to process "events" and get the "values" of the inputs
while True:
    event, values = window.read()
    if event in (sg.WIN_CLOSED, '退出'):
        break
    if event == '开始' and not starting:
        starting = True
        # Clear the text area
        window['-TEXTAREA-'].update('')
        # Get the IP and range from the inputs
        ip_base = values['-IP-']
        if not is_valid_ip(ip_base):
            sg.popup("请输入正确的IP地址格式，例如：192.168.0.1")
            continue
        ip_range = values['-RANGE-']
        if not is_valid_num(ip_range):
            sg.popup("请输入有效的数字范围，例如：1-255")
            continue
        # Ping the range of IP addresses
        # ping_range(ip_base, ip_range)
        threading.Thread(target=ping_range, args=(ip_base, ip_range)).start()
    if event == "停止":
        starting = False

# Close the window
window.close()
